
# -*- coding: utf-8 -*-

import os
import json
import shutil
import urllib
import qrcode
import base64
import urllib2
import StringIO
import tornado.web
from config import Config
from models.User import User
from controllers.BaseController import BaseController

class UserController(BaseController):

	@staticmethod
	def filterUserList(filterData):
		urlFilter = "%s?%s" % (Config.USERS_WEBSERVICE_URL, urllib.urlencode({"query": filterData if filterData else ""}))
		try:
			response = urllib2.urlopen(urllib2.Request(urlFilter))
			respData = response.read()
			parsed = json.loads(unicode(respData, "ISO-8859-1"))
			returnList = []
			for emp in parsed["employees"]:
				returnList.append({"data": emp["id"], "value": unicode(emp["nombre"])})
			return returnList
		except:
			pass
		return []

	@tornado.web.authenticated
	def get(self):
		if Config.isAdmin(self.get_secure_cookie('userid')):
			if self.request.path == "/users/" or self.request.path == "/users/add":
				self.render("adduser.html", userid=self.get_secure_cookie('userid'), dst="/users/addphotos")
				return
			if self.request.path == "/users/del":
				self.render("deluser.html", userid=self.get_secure_cookie('userid'))
				return
			elif self.request.path == "/users/filter":
				self.write(json.dumps({
					"query": "Unit",
					"suggestions": UserController.filterUserList(self.get_argument("query", None))
				}))
				return
			elif self.request.path == "/users/addphotos":
				user = User.get(User.username == self.get_secure_cookie('user'))
				if user:
					self.render("addphotos.html", userid=self.get_secure_cookie('user'), username=self.get_secure_cookie('name'))
					return
				self.redirect("/users/adduser")
				return
			if self.request.path == "/users/userextraphoto":
				self.render("adduser.html", userid=self.get_secure_cookie('userid'), dst="/users/extraphotos")
				return
			elif self.request.path == "/users/extraphotos":
				user = User.get(User.username == self.get_secure_cookie('user'))
				if user:
					self.render("extraphotos.html", userid=self.get_secure_cookie('user'), username=self.get_secure_cookie('name'))
					return
				self.redirect("/users/userextraphoto")
				return
			elif self.request.path == "/users/qrgen":
				self.render("qrgen.html", userid=self.get_secure_cookie('userid'))
				return
		self.redirect("/users/logout")

	@tornado.web.authenticated
	def post(self):
		if Config.isAdmin(self.get_secure_cookie('userid')):
			if self.request.path == "/users/name":
				user = self.get_argument("user", None)
				name = self.get_argument("name", None)
				if user and name:
					u = User.get_or_create(username=user)
					u.name = name
					u.persist()
					self.set_secure_cookie('user', user)
					self.set_secure_cookie('name', name)
					return
				raise tornado.web.HTTPError(400)
			elif self.request.path == "/users/photonumber":
				photonumber = self.get_argument("photonumber", None)
				if photonumber:
					Config.PHOTONUMBER = photonumber
					self.write('success')
					return
				raise tornado.web.HTTPError(400)
			elif self.request.path == "/users/del":
				username = self.get_argument("username", None)
				if username and Config.USER_WEBSERVICE_LIST.has_key(username):
					userpath = "data/images/%s" % username
					if os.path.isdir(userpath):
						shutil.rmtree(userpath)
					self.write('success')
					return
			elif self.request.path == "/users/qrgen":
				username = self.get_argument("username", None)
				if username and Config.USER_WEBSERVICE_LIST.has_key(username):
					buf = StringIO.StringIO()
					qr = qrcode.QRCode(
							version=1,
							error_correction=qrcode.constants.ERROR_CORRECT_L,
							box_size=10,
							border=4,
					)
					qr.add_data(username)
					qr.make(fit=True)

					img = qr.make_image()
					img.save(buf, "PNG")
					b64img = base64.b64encode(buf.getvalue())
					self.write(json.dumps({"success": True, "data": b64img}))
					return
				self.write(json.dumps({"success": False, "data": None}))
				return
		raise tornado.web.HTTPError(404)
